#!/usr/bin/env bash

# 创建一个用于Tab键补全的标签
# 参数: complementary words
# 返回: tabmark
create_cmd_tab()
{
    [[ -d ${CMD_TAB_PATH} ]] || return 1
    new_tab_name="$RANDOM$RANDOM"
    tab_list=("$*")
    while [[ -d ${CMD_TAB_PATH}/$new_tab_name ]]; do
        new_tab_name="$RANDOM$RANDOM"
    done
    mkdir -p ${CMD_TAB_PATH}/$new_tab_name
   
    for tab_name in ${tab_list[@]}; do
        echo -n "" > ${CMD_TAB_PATH}/$new_tab_name/$tab_name
    done
    echo "$new_tab_name"
    return 0
}

# 添加一个新的补全标签
# 参数:
#    $1: 补全标签
#    $2: 新值(可多个)
add_cmd_to_tab()
{
    new_tab_name="$1"
    tab_list=("${@:2:$#-1}")
    [[ -d ${CMD_TAB_PATH}/$new_tab_name ]] || return 1
    for tab_name in ${tab_list[@]}; do
        echo -n "" > ${CMD_TAB_PATH}/$new_tab_name/$tab_name
    done
    return 0
}

# 补全标签删除一个值从
# 参数:
#    $1: 补全标签
#    $2-: 值
rm_cmd_from_tab()
{
    new_tab_name="$1"
    tab_list=("${@:2:$#-1}")
    [[ -d ${CMD_TAB_PATH}/$new_tab_name ]] || return 1
    for tab_name in ${tab_list[@]}; do
        [[ -f ${CMD_TAB_PATH}/$new_tab_name/$tab_name ]] && rm -f ${CMD_TAB_PATH}/$new_tab_name/$tab_name
    done
    return 0
}

# 删除一个补全标签
delete_cmd_tab()
{
    [[ -d ${CMD_TAB_PATH} ]] || return 1
    [[ -d ${CMD_TAB_PATH}/$1 ]] && rm -rf ${CMD_TAB_PATH}/$1 || true
    return 0
}

# 读取用户输入
# --tab 补全标签，可以增加Tab键自动补全
# -p "提示"，可以自定义提示
cmd_read()
{
    [[ -d ${CMD_TAB_PATH} ]] || return 1
    [[ -d ${CMD_DEFAULT_TAB_PATH} ]] || return 1

    _read_env_dir="${CMD_TAB_PATH}/$(find_arg "--tab" $*)" || _read_env_dir=""
    if [[ "$_read_env_dir" != "" && -d $_read_env_dir ]]; then
        cd $_read_env_dir
    else
        cd ${CMD_DEFAULT_TAB_PATH}
    fi
    # apply history
    apply_history
    eval PS_G_="$(echo "$CMD_PS_G")"
    echo "$PS_G_" > $PS_G_FILE
	# read
    IFS=$'\n' read  -p "$PS_G_" -e cmd_line
    # trim
    cmd_line="$(trim_all "$cmd_line")"
	# record history
    record_history "${cmd_line}"
    echo "${cmd_line}"
    cd - >>/dev/null
}

module_init()
{
    # 设置环境变量
    export READ_CTRL_DIR="${TmpDir}/module/read_control"
    export CMD_TAB_PATH="${READ_CTRL_DIR}/TAB"
    export PS_G_FILE="${READ_CTRL_DIR}/.PS_G_"
    export CMD_PS_G='~\\$COMMAND_NAME: '
    # 创建临时文件夹
    [[ -d ${READ_CTRL_DIR} ]] || mkdir -p ${READ_CTRL_DIR}
    [[ -d ${CMD_TAB_PATH} ]] || mkdir -p ${CMD_TAB_PATH}
    export CMD_DEFAULT_TAB_PATH=${CMD_TAB_PATH}/"$(create_cmd_tab)"
    debug_echo "Read module is ok!"
}

module_exit()
{
    unset READ_CTRL_DIR
    unset CMD_TAB_PATH
    unset CMD_PS_G
    unset CMD_DEFAULT_TAB_PATH
    [[ -d $READ_CTRL_DIR ]] && rm -rf $READ_CTRL_DIR
    debug_echo "Read module exited!"
}